package com.mqqzt.douban;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.google.gdata.client.douban.DoubanService;
import com.google.gdata.data.PlainTextConstruct;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.os.Build;
import android.util.Log;

public class MyCrashHandler implements UncaughtExceptionHandler {
	private static MyCrashHandler myCrashHandler;
	private Context context;
	private MyCrashHandler(){
		
	}
	public void init(Context context){
		this.context = context;
	}
	public static synchronized MyCrashHandler getInstance(){
		if(myCrashHandler == null){
			myCrashHandler = new MyCrashHandler();
		}
		return myCrashHandler;
	}
	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		StringBuilder sb = new StringBuilder();
		try {
			PackageInfo packInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			sb.append("程序的版本号为：" + packInfo.versionName);
			sb.append("\n");
			
			Field[] fields = Build.class.getDeclaredFields();
			for(int i = 0; i < fields.length; i++){
				fields[i].setAccessible(true);
				String name = fields[i].getName();
				sb.append(name + " = ");
				String value = fields[i].get(null).toString();
				sb.append(value);
				sb.append("\n");
			}
			
			StringWriter writer = new StringWriter();
			PrintWriter printWriter = new PrintWriter(writer);
			ex.printStackTrace(printWriter);
			String result = writer.toString();
			sb.append(result);
			
			String apiKey = "0c51c1ba21ad8cfd24f5452e6508a6f7";
			String secret = "359e16e5e5c62b6e";

			DoubanService myService = new DoubanService("黑马小瓣瓣", apiKey,
					secret);
			SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
			String accesstoken = sp.getString("accesstoken", "");
			String tokensecret = sp.getString("tokensecret", "");
			myService.setAccessToken(accesstoken, tokensecret);
			
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
			String title = format.format(new Date(System.currentTimeMillis()));
			myService.createNote(new PlainTextConstruct(title), new PlainTextConstruct(sb.toString()), "private", "no");
			
			Log.e("error", sb.toString());
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		android.os.Process.killProcess(android.os.Process.myPid());

	}

}
